<template>
  <XenPageLayout title="创建活动" title-align="left">
    <view class="activityForm">
      <uni-forms
        ref="form"
        :modelValue="formData"
        :rules="rules"
        label-position="top"
        label-width="150px"
      >
        <!-- 参与者类型 -->
        <uni-forms-item
          name="participantType"
          label="参与者类型"
          :required="true"
        >
          <uni-data-select
            v-model="formData.participantType"
            :localdata="participantTypeOptions"
            placeholder="请选择参与者类型"
            @blur="validateField('participantType')"
          />
        </uni-forms-item>
        <!-- 姓名/公司名 -->
        <uni-forms-item
          name="participantName"
          label="姓名/公司名"
          :required="true"
        >
          <uni-easyinput
            v-model="formData.participantName"
            placeholder="请输入您的姓名/公司名"
            @blur="validateField('participantName')"
          />
        </uni-forms-item>
        <!-- 手机号 -->
        <uni-forms-item name="phone" label="联系电话" :required="true">
          <uni-easyinput
            v-model="formData.phone"
            placeholder="请输入您的联系电话"
            type="number"
            :maxlength="11"
            @blur="validateField('phone')"
          />
        </uni-forms-item>

        <uni-forms-item name="address" label="详细地址" :required="true">
          <uni-easyinput
            v-model="formData.address"
            placeholder="请输入您的详细地址"
            @blur="validateField('address')"
          />
        </uni-forms-item>

        <uni-forms-item name="description" label="描述">
          <uni-easyinput
            v-model="formData.description"
            placeholder="请输入您的描述"
          />
        </uni-forms-item>

        <uni-forms-item name="images" label="上传图片" :required="true">
          <view class="upload-container">
            <view class="upload-list">
              <view
                class="upload-item"
                v-for="(item, index) in imagePreviewList"
                :key="index"
              >
                <image
                  class="upload-image"
                  :src="item.path"
                  mode="aspectFill"
                ></image>
                <text class="delete-icon" @click="deleteImage(index)">×</text>
                <view class="upload-status" v-if="item.status !== 'success'">
                  <text
                    v-if="item.status === 'uploading'"
                    class="status-text uploading"
                    >上传中...</text
                  >
                  <text v-if="item.status === 'error'" class="status-text error"
                    >上传失败</text
                  >
                  <text
                    v-if="item.status === 'error'"
                    class="retry-btn"
                    @click="retryUpload(index)"
                    >重试</text
                  >
                </view>
              </view>
              <view class="upload-button" @click="chooseImage">
                <text class="upload-icon">+</text>
              </view>
            </view>
            <text class="upload-tip">可上传多张图片（至少上传一张）</text>
          </view>
        </uni-forms-item>

        <view class="form-button">
          <text class="submit-tip"
            >注意：每个活动只能提交一次，提交后无法修改</text
          >
          <button class="submit-button" @click="submitForm">提交</button>
        </view>
      </uni-forms>
    </view>
  </XenPageLayout>
</template>
<script lang="ts" setup>
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import { reactive, ref, computed } from "vue";
import { SysActivityParticipationApi } from "./api";
import { onLoad } from "@dcloudio/uni-app";
import { uploadImage } from "../../../utils/unirequest";
import type { IImagesIds } from "./api/interface";
// 添加事件总线导入
import { ActivityEvents } from "../../../utils/eventBus";

const form = ref();
const validateField = (field: string) => {
  form.value.validateField(field);
};

// 参与者类型选项
const participantTypeOptions = [
  { value: "1", text: "个人" },
  { value: "2", text: "公司" },
];

// 图片上传列表，包含状态信息
const imagePreviewList = ref<
  Array<{
    path: string; // 图片本地路径或预览URL
    id?: string; // 上传成功后的图片ID
    status: "uploading" | "success" | "error"; // 上传状态
    errorMsg?: string; // 错误信息
    imagesOld?: string; // 服务器返回的图片ID
  }>
>([]);

// 计算已成功上传的图片ID列表
const uploadedImageIds = computed(() => {
  return imagePreviewList.value
    .filter((item) => item.status === "success" && item.imagesOld)
    .map((item, index) => ({
      FileId: item.imagesOld as string,
      Order: index,
    }));
});

const formData = reactive({
  activityId: "",
  participantType: "",
  participantName: "",
  phone: "",
  address: "",
  images: [] as string[],
  description: "",
  wxOpenid: "",
});

onLoad((options: any) => {
  formData.activityId = options.activityId;
  formData.wxOpenid = uni.getStorageSync("wxOpenid");
  // 获取本地缓存中的参与类型、姓名/公司名、联系电话、详细地址
  formData.participantType = uni.getStorageSync("participantType");
  formData.participantName = uni.getStorageSync("participantName");
  formData.phone = uni.getStorageSync("phone");
  formData.address = uni.getStorageSync("address");
});

// 表单校验规则
const rules = {
  name: {
    rules: [{ required: true, errorMessage: "请输入姓名" }],
  },
  participantType: {
    rules: [{ required: true, errorMessage: "请选择参与者类型" }],
  },
  participantName: {
    rules: [{ required: true, errorMessage: "请输入姓名/公司名" }],
  },
  phone: {
    rules: [
      { required: true, errorMessage: "请输入联系电话" },
      { pattern: /^1\d{10}$/, errorMessage: "手机号格式不正确" },
    ],
  },
  address: {
    rules: [{ required: true, errorMessage: "请输入地址" }],
  },
};

// 上传单张图片 - 使用封装的方法
const uploadImageWrapper = async (
  filePath: string,
  index: number,
): Promise<string> => {
  try {
    return await uploadImage(filePath);
  } catch (error) {
    console.error("上传图片失败：", error);
    throw error;
  }
};

// 选择图片并立即上传
const chooseImage = () => {
  uni.chooseImage({
    count: 9999,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      const paths = res.tempFilePaths as string[];
      // 为每个新图片生成唯一ID并添加到预览列表
      const newImagesWithId = paths.map((path) => ({
        id: Date.now() + "_" + Math.random().toString(36).substr(2, 9), // 生成唯一ID
        path,
        status: "uploading" as const,
      }));

      // 添加到预览列表
      const newImagesList = [...imagePreviewList.value, ...newImagesWithId];
      imagePreviewList.value = newImagesList;

      // 逐个上传新添加的图片
      for (let i = 0; i < newImagesWithId.length; i++) {
        const currentImage = newImagesWithId[i];
        try {
          const imageId = await uploadImageWrapper(currentImage.path, i);

          // 通过唯一ID查找图片在当前列表中的索引
          const currentIndex = imagePreviewList.value.findIndex(
            (item) => item.id === currentImage.id,
          );

          if (currentIndex !== -1) {
            // 更新上传状态和ID - 使用Vue的响应式方法
            if (imageId) {
              imagePreviewList.value[currentIndex].status = "success";
              imagePreviewList.value[currentIndex].id = imageId;
              imagePreviewList.value[currentIndex].imagesOld = imageId;
            } else {
              imagePreviewList.value[currentIndex].status = "error";
              imagePreviewList.value[currentIndex].errorMsg =
                "上传失败，返回ID为空";
            }
          }
        } catch (error) {
          console.error("图片上传失败:", error);
          const currentIndex = imagePreviewList.value.findIndex(
            (item) => item.id === currentImage.id,
          );

          if (currentIndex !== -1) {
            imagePreviewList.value[currentIndex].status = "error";
            imagePreviewList.value[currentIndex].errorMsg = "上传失败，请重试";
          }
        }
      }
    },
  });
};

// 删除图片
const deleteImage = (index: number) => {
  imagePreviewList.value.splice(index, 1);
};

// 重试上传
const retryUpload = async (index: number) => {
  const imageInfo = imagePreviewList.value[index];
  if (imageInfo && imageInfo.status === "error") {
    imageInfo.status = "uploading";

    try {
      const imageId = await uploadImageWrapper(imageInfo.path, index);
      if (imageId) {
        imageInfo.status = "success";
        imageInfo.id = imageId;
        imageInfo.imagesOld = imageId;
        imageInfo.errorMsg = undefined;
      } else {
        imageInfo.status = "error";
        imageInfo.errorMsg = "上传失败，返回ID为空";
      }
    } catch (error) {
      console.error("重试上传失败:", error);
      imageInfo.status = "error";
      imageInfo.errorMsg = "重试失败，请再次尝试";
    }
  }
};

// 提交表单
const submitForm = async () => {
  await form.value.validate();

  // 首先检查是否有正在上传的图片
  if (imagePreviewList.value.some((item) => item.status === "uploading")) {
    uni.showToast({ title: "图片正在上传中，请等待上传完成", icon: "none" });
    return;
  }

  // 检查是否有成功上传的图片
  if (uploadedImageIds.value.length === 0) {
    if (imagePreviewList.value.length === 0) {
      uni.showToast({ title: "请上传至少一张图片", icon: "none" });
    } else {
      uni.showToast({ title: "图片上传失败，请重试", icon: "none" });
    }
    return;
  }
  // 使用已上传成功的图片ID
  formData.images = uploadedImageIds.value.map((item) => item.FileId);


  // 提交表单数据
  await SysActivityParticipationApi().add({
    Entity: {
      ActivityId: formData.activityId,
      Address: formData.address,
      Description: formData.description,
      Name: formData.participantName,
      ParticipantType: formData.participantType,
      Phone: formData.phone,
    },
    SelectedActivityImagesIds: uploadedImageIds.value as IImagesIds[],
  });

  uni.showToast({ title: "提交成功", icon: "success" });

  // 提交成功后保存参与类型、姓名/公司名、联系电话、详细地址到本地缓存
  uni.setStorageSync("participantType", formData.participantType);
  uni.setStorageSync("participantName", formData.participantName);
  uni.setStorageSync("phone", formData.phone);
  uni.setStorageSync("address", formData.address);

  // 发布活动参与更新事件
  ActivityEvents.emit("custom", {
    id: formData.activityId,
    customAction: "join",
  });

  // 延迟跳转，确保事件被处理
  setTimeout(() => {
    uni.redirectTo({
      url: `/subpkg-activity/activity/sysactivityparticipation/index?activityId=${formData.activityId}`,
    });
  }, 1500); // 增加延迟时间
};
</script>

<style lang="scss" scoped>
.activityForm {
  min-height: 100vh;
  padding: 30rpx;

  &-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .upload-container {
    width: 100%;

    .upload-list {
      display: flex;
      flex-wrap: wrap;

      .upload-item,
      .upload-button {
        width: 200rpx;
        height: 200rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        position: relative;
      }

      .upload-item {
        .upload-image {
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }

        .delete-icon {
          position: absolute;
          top: -16rpx;
          right: -16rpx;
          width: 40rpx;
          height: 40rpx;
          line-height: 36rpx;
          text-align: center;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          border-radius: 50%;
          font-size: 32rpx;
        }

        .upload-status {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          font-size: 24rpx;
          padding: 6rpx;
          text-align: center;

          .status-text {
            display: block;

            &.uploading {
              color: #fff;
            }

            &.error {
              color: #ff6b6b;
            }
          }

          .retry-btn {
            display: inline-block;
            background-color: #b88e67;
            color: #fff;
            padding: 4rpx 12rpx;
            border-radius: 8rpx;
            margin-top: 4rpx;
          }
        }
      }

      .upload-button {
        border: 2rpx dashed #ccc;
        border-radius: 8rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .upload-icon {
          font-size: 64rpx;
          color: #999;
        }
      }
    }

    .upload-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }

  .form-button {
    margin-top: 50rpx;

    .submit-tip {
      display: block;
      text-align: center;
      color: #ff6b6b;
      font-size: 24rpx;
      margin-bottom: 20rpx;
    }

    .submit-button {
      color: #fff;
      width: 90%;
      background-color: #b88e67;
      box-shadow: 0 4px 12px rgba(184, 142, 103, 0.2);
      border-radius: 50rpx;
    }
  }
}
</style>
